package com.sdruixinggroup.mondayb2b.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.ModelBeen;
import com.sdruixinggroup.mondayb2b.ui.WebActivity;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by 00029935 on 2017/11/17.
 */

public class RegisterFragment extends BaseFragment {
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_sms)
    EditText etSms;
    @BindView(R.id.tv_send_sms)
    TextView tvSendSms;
    @BindView(R.id.et_psd)
    EditText etPsd;
    @BindView(R.id.et_psd_again)
    EditText etPsdAgain;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.invite_ll)
    LinearLayout inviteLl;

    @BindView(R.id.topbar_left)
    ImageView topbarLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.loading)
    ProgressBar loading;
    @BindView(R.id.et_invite_code)
    EditText etInviteCode;
    private boolean isForgetPSWD;
    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tvSendSms.setText((millisUntilFinished / 1000) + "秒后可重发");
            tvSendSms.setClickable(false);
        }

        @Override
        public void onFinish() {
            tvSendSms.setEnabled(true);
            tvSendSms.setClickable(true);
            tvSendSms.setText("获取验证码");
        }
    };
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isForgetPSWD = getActivity().getIntent().getBooleanExtra("isForgetPSWD", false);
    }

    @Override
    protected int getInflateLayout() {
        return R.layout.register_fragment;
    }

    @Override
    protected void setUpView(View view) {
        topbarLeft.setImageResource(R.mipmap.registration_back);

        if (isForgetPSWD) {
            tvTitle.setText("忘记密码");
            tvTip.setVisibility(View.GONE);
            tvRegister.setText("确定");
            inviteLl.setVisibility(View.GONE);
        }
        tvTip.setText(Html.fromHtml("<font  color=#383838>点击注册，即表示您同意</font><font  color=#28d46d>《粒到农资注册协议》</font>"));
        tvTip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toWebView("agreement?");
            }
        });
    }

    private void toWebView(String param) {
        Intent intent = new Intent(getContext(), WebActivity.class);
        intent.putExtra(WebActivity.INTENT_EXTRA_BEGIN_URL, param);
        startActivity(intent);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @OnClick(R.id.tv_register)
    public void onClick() {

        String phone = etPhone.getText().toString().trim();
        String sms = etSms.getText().toString().trim();
        String psd = etPsd.getText().toString().trim();
        String psdAgain = etPsdAgain.getText().toString().trim();

        if (isForgetPSWD) {
            forgetPSWD(phone, psd, psdAgain, sms);
        } else {

            if (!psd.equals(psdAgain)) {
                showMsgToast("您两次输入的密码不一致");
                return;
            }

            register(phone, psd, psdAgain, sms);
        }

    }

    @OnClick(R.id.topbar_left)
    public void onClickFinish() {
        getActivity().finish();
    }

    @OnClick(R.id.tv_send_sms)
    public void onClickSMS() {
        String phone = etPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            showMsgToast("请输入手机号码");
            return;
        }

        if (isForgetPSWD) {
            smsforgetPSWD(phone);
        } else {
            registerSMS(phone);
        }
        restart();
    }

    private void registerSMS(String phone) {
        loading.setVisibility(View.VISIBLE);
        String url = API.SMS_REGISTER + phone;

        HashMap<String, String> header = new HashMap<>();
        header.put("Accept", "*/*");

        TypeToken<ModelBeen<Object>> typeToken = new TypeToken<ModelBeen<Object>>() {
        };

        OkHttpUtils.post().url(url).params(header).build().execute(new ObjectCallBack<ModelBeen<Object>>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {
                loading.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(ModelBeen<Object> response, int id) {
                if (0 == response.err_code) {
                    showMsgToast("发送成功");
                } else {
                    showMsgToast(response.err_msg);
                }

                loading.setVisibility(View.GONE);
            }
        });

    }


    private void register(String mobile, String password, String verify, String captcha) {
        loading.setVisibility(View.VISIBLE);
        String  inviteCode = etInviteCode.getText().toString().trim();
        String url = API.REGISTER_MOBILE + "mobile=" + mobile + "&password=" + password + "&verify=" + verify + "&captcha=" + captcha+"&invitation_code="+inviteCode;
        HashMap<String, String> header = new HashMap<>();
        header.put("Accept", "*/*");

        TypeToken<ModelBeen<Object>> typeToken = new TypeToken<ModelBeen<Object>>() {
        };

        OkHttpUtils.post().url(url).params(header).build().execute(new ObjectCallBack<ModelBeen<Object>>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {
                loading.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(ModelBeen<Object> response, int id) {
                if (0 == response.err_code) {
                    showMsgToast("注册成功，请登陆");
                    getActivity().finish();
                } else {
                    showMsgToast(response.err_msg);
                }

                loading.setVisibility(View.GONE);
            }
        });
    }

    private void forgetPSWD(String mobile, String password, String verify, String captcha) {
        loading.setVisibility(View.VISIBLE);

        String url = API.PASSWORD_FORGOT + "mobile=" + mobile + "&password=" + password + "&verify=" + verify + "&captcha=" + captcha;
        HashMap<String, String> header = new HashMap<>();
        header.put("Accept", "*/*");

        TypeToken<ModelBeen<Object>> typeToken = new TypeToken<ModelBeen<Object>>() {
        };

        OkHttpUtils.post().url(url).params(header).build().execute(new ObjectCallBack<ModelBeen<Object>>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {
                loading.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(ModelBeen<Object> response, int id) {
                if (0 == response.err_code) {
                    showMsgToast("密码修改成功，请登陆！");
                    getActivity().finish();
                } else {
                    showMsgToast(response.err_msg);
                }

                loading.setVisibility(View.GONE);
            }
        });
    }

    private void smsforgetPSWD(String phone) {
        loading.setVisibility(View.VISIBLE);
        String url = API.SMS_FORGOT_PASSWORD + phone;
        HashMap<String, String> header = new HashMap<>();
        header.put("Accept", "*/*");

        TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>() {
        };

        OkHttpUtils.post().url(url).params(header).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {
                loading.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(ModelBeen response, int id) {
                if (0 == response.err_code) {
                    showMsgToast("发送成功");
                } else {
                    showMsgToast(response.err_msg);
                }

                loading.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 开始倒计时
     */
    public void restart() {
        timer.start();
    }

    /**
     * 取消倒计时
     */
    public void oncancel() {
        timer.cancel();
    }
}
